package cn.newtouch.exception;

import cn.newtouch.enums.GlobalEnum;
import cn.newtouch.result.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * 自定义全局异常
 */
@RestControllerAdvice
@Component
@Slf4j
public class GlobalException {

    @ExceptionHandler(Exception.class)
    public JsonResult exceptionHandler(Exception e){
        e.printStackTrace();
        log.info("捕捉到了Exception异常："+e.getMessage());
        return JsonResult.error(GlobalEnum.ERROR);
    }

    //有具体的异常类，先找具体的，没有具体的就找父类
    @ExceptionHandler(GlobalCustomException.class)
    public JsonResult GlobalCustomExceptionHandler(GlobalCustomException e){
        e.printStackTrace();
        log.info("捕捉到了GlobalCustomException异常："+e.getErrorMessage()+"异常码："+e.getErrorCode());
        return JsonResult.error(GlobalEnum.PARAM_IS_NULL_ERROR);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        e.printStackTrace();

        StringBuilder stringBuilder = new StringBuilder();

        e.getBindingResult().getAllErrors().forEach(item->{
            stringBuilder.append(item.getDefaultMessage());
        });
        log.info("捕捉到了MethodArgumentNotValidException异常："+stringBuilder.toString());
        return JsonResult.error(stringBuilder.toString());
    }


}
